package com.example.prison.protocol;

import com.example.prison.entity.DeviceInfo;
import com.example.prison.util.APIUtil;
import com.example.prison.util.Crc16Util;
import com.example.prison.util.Crc8Util;
import lombok.extern.slf4j.Slf4j;

import java.io.*;
import java.net.Socket;
import java.util.Arrays;

import static com.example.prison.protocol.StringUtil.byteToPrintAsciiHexString;

@Slf4j
public class Client {

    public static void main(String[] args)  {
        try {
        Socket socket = new Socket("10.10.10.110",8886);//创建Socket对象(客户端)，指定服务端的ip和端口号
//            Socket socket = new Socket("192.168.4.101", 8886);
            socket.setSoTimeout(2000);//设置超时时间为10秒
//            log.info("连接设备");
            //获取通往服务端的OutputStream
            OutputStream out= socket.getOutputStream();//获取一个输出流，向服务端发送信息
            byte[] message = new byte[]{0x03, 0x00, 0x01, 0x00, 0x07};  //发送的固定消息  查询设备状态
//            byte[] sendInfo = new byte[]{0x01, 0x03, 0x00, 0x03, 0x00, 0x01};  //发送的消息  查询设备类型

            byte[] sendMessage = new byte[6];
            sendMessage = APIUtil.combineArrays(APIUtil.intToBytes(1), message);//查询设备状态
            byte[] crc = Crc16Util.getCrc16(sendMessage);
            byte[] CRC8 = APIUtil.intToBytes(Crc8Util.CRC8(sendMessage, 0 , sendMessage.length));
            System.out.println("CRC8校验"+ Arrays.toString(CRC8));
            byte[] crc16 = new byte[1];
            System.arraycopy(crc, 0, crc16, 0, 1);
//            byte[] sendInfo = APIUtil.combineArrays(sendMessage, crc16);
            byte[] sendInfo = APIUtil.combineArrays(sendMessage, CRC8);
//            log.info("二进制crc校验结果" + Arrays.toString(crc));
            log.info("查询设备类型=====》[" + byteToPrintAsciiHexString(sendInfo)+"]");
            out.write(sendInfo);//往服务端写数据
            out.flush();
//            log.info("等待服务端响应");
            //获取输入流，用来读取服务端发过来的数据
            InputStream inputStream = socket.getInputStream();//获取一个输入流，接收服务端的信息
            byte[] bs = new byte[18];
            inputStream.read(bs);
            String res1 = byteToPrintAsciiHexString(bs);  //输出十六进制，调用刚刚的转换函数
            log.info("服务端响应====>["+res1+"]");
//            log.info("解码====>"+Arrays.toString(APIUtil.decodeType(res1)));
            log.info("解码====>"+Arrays.toString(APIUtil.decodeSmallStatus(res1)));
            log.info("释放资源");
            socket.shutdownOutput();//关闭输出流,关闭相对应的资源
            inputStream.close();
            out.close();
            socket.close();
        } catch (IOException e) {
            System.out.println("连接超时");
            log.info("连接超时");
        }
    }


}
